<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.sql.*"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.io.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
	String newpath="";         
    String newSQLpath="";
%>
<%
 	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 	if (!isMultipart) {} 
 	else {
 		FileItemFactory factory = new DiskFileItemFactory();
   		ServletFileUpload upload = new ServletFileUpload(factory);
   		List items = null;
   		try {
   			items = upload.parseRequest(request);
   		} catch (FileUploadException e) {
   			e.printStackTrace();
   		}		
   	Iterator itr = items.iterator();
   	while (itr.hasNext()) {
   		FileItem item = (FileItem) itr.next();
   		try {
   			String itemName = item.getName();
   			newpath = config.getServletContext().getRealPath("/")+itemName;
   			newSQLpath+=itemName;
   			File savedFile = new File(newpath);
   			item.write(savedFile);
   			} catch (Exception e) {
   				e.printStackTrace();
  			}
   		}
   	}

%>
<%
	Class.forName("com.mysql.jdbc.Driver");
	Connection con = null;
	Statement smt = null;
	ResultSet rst = null;
	String link = "";
	StringBuffer tmp = new StringBuffer();
	int i = 0;
	String path = request.getRealPath("/");
	try {
		String username = "root";
		String password = "root";
		String url = "jdbc:mysql://127.0.0.1:3306/banhang?useUnicode=true&characterEncoding=UTF-8";
		con = DriverManager.getConnection(url, username, password);
		System.out.println("Da ket noi CSDL");
		smt = con.createStatement();
		rst = smt.executeQuery("select * from ads");
		rst.next();
		link = rst.getString("link");
		path = path+link;
		tmp.delete(0, tmp.length());
		for (i = 0; i < path.length(); i++) {
			if (path.charAt(i) != '\\') tmp.append(path.charAt(i)); 
			else tmp.append('/');
		}
		path = tmp.toString();
		File f = new File(path);
		System.out.println(f.delete());
		System.out.println("UPDATE ads SET link='"+newSQLpath+"' WHERE id='1'");
		smt.execute("UPDATE ads SET link='"+newSQLpath+"' WHERE id='1'");
		newSQLpath="";
		con.close();
		System.out.println("Dong ket noi");
		response.sendRedirect("adsmanager.jsp");
	}
	catch (Exception e) {
		e.printStackTrace();
		System.out.println("KHONG KET NOI DUOC");
	}
%>
</body>
</html>